package com.example.javaeekeshe.controller;

import com.example.javaeekeshe.pojo.AccountBean;
import com.example.javaeekeshe.pojo.AdBean;
import com.example.javaeekeshe.pojo.GoodsBean;
import com.example.javaeekeshe.service.IAdService;
import com.example.javaeekeshe.service.IGoodsCarService;
import com.example.javaeekeshe.service.impl.GoodsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 主页及详情页
 */
@Controller
public class IndexController {
    @Autowired
    GoodsServiceImpl goodsService;
    @Autowired
    IGoodsCarService goodsCarService;
    @Autowired
    IAdService adService;


    /**
     * 详情页跳转
     * @return
     */
    @RequestMapping("/xiangqing/{id}")
    public String toXiangqing(@PathVariable("id") Integer id,Model model){
        //根据id查找商品
        GoodsBean goodsBean = goodsService.selectGoodById(id);
        model.addAttribute("good",goodsBean);
        String[] colors = goodsBean.getColor().split("_");
        model.addAttribute("colors",colors);
        return "/xiangqing";
    }

    /**
     * 商城首页
     */
    @RequestMapping({"/","/index","/index.html"})
    public String toindex(Model model){
        List<GoodsBean> goodsBeans = goodsService.selectAllGood();
        model.addAttribute("goods",goodsBeans);
        List<AdBean> adBeans = adService.selectAllAd();
        model.addAttribute("ads",adBeans);
        return "/index";
    }

    /**
     * 加入购物车
     * @param id
     * @return
     */
    @RequestMapping("/addShangPin")
    public String addShangPin(int id, String color, Model model, HttpSession session){
        AccountBean loginUser = (AccountBean) session.getAttribute("loginUser");
        //加入购物车
        if (goodsCarService.addGoodsToCar(loginUser.getId(),id,color)) {
            return "redirect:/buy/car";
        }else {
            model.addAttribute("msg","加入购物车失败");
            return "/index";
        }

    }
}
